<template>
  <el-dialog
    title="添加或修改分类"
    :visible.sync="dialogFormVisible"
    :before-close="hide"
  >
    <el-form :model="form">
      <el-form-item label="分类等级或名称" :label-width="formLabelWidth">
        <el-select v-model="selectedItemId" style="width:100%;">
          <el-option
            v-for="item in tableDataForAdd"
            :key="item._id"
            :label="item.name"
            :value="item._id"
            placeholder="请选择分类名称"
            style="width:100%;"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请输入分类名称" :label-width="formLabelWidth">
        <el-input v-model="form.newName" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="hide">取 消</el-button>
      <el-button type="primary" @click="enter">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Prop, Vue, Emit } from "vue-property-decorator";
import { categoryType, failDataType } from "CustomTypes";
import { concat, isEqual, isUndefined } from "lodash";
import { addCategorys, updateCategorys } from "@/apis/Category";
import { getReqDataNew } from "@/utils/http";
import { MessageBox } from "element-ui";

@Component({ name: "AddFormCategory" })
export default class AddFormCategory extends Vue {
  @Prop()
  private tableData!: Array<categoryType>;
  @Prop()
  private handleRefresh!: any;
  @Prop()
  private itemData!: categoryType;
  public dialogFormVisible = false;
  private formLabelWidth = "120px";
  private lv1Name = "一级分类";
  private min = 5;
  private max = 10;

  get tableDataForAdd() {
    return concat(
      [
        {
          _id: "-1",
          name: this.lv1Name,
          parentId: "0"
        }
      ],
      this.tableData
    );
  }

  private form = {
    newName: "",
    selectedItemId: ""
  };

  get selectedItemId() {
    this.form.selectedItemId = this.itemData._id;
    return this.itemData._id;
  }

  async enter() {
    const { newName, selectedItemId } = this.form;
    const selectedItem = this.tableDataForAdd.find(item =>
      isEqual(item._id, selectedItemId)
    );
    if (isUndefined(selectedItem)) return;
    const { _id, parentId } = selectedItem;
    const result = isEqual("-1", _id)
      ? await addCategorys(newName, parentId)
      : await updateCategorys(_id, newName);
    const { flag, data } = getReqDataNew(result);

    this.form = {
      newName: "",
      selectedItemId: ""
    };

    if (flag) {
      // 这里需要刷新父类网页，重新加载父类数据。
      this.handleRefresh();
      this.hide();
      return;
    }

    MessageBox.alert((data as failDataType).msg, {
      confirmButtonText: "确定",
      type: "error"
    });
    this.hide();
  }

  @Emit("hide-add-form-category")
  hide() {
    this.form = {
      newName: "",
      selectedItemId: ""
    };
    this.dialogFormVisible = false;
  }
}
</script>

<style scoped></style>
